package com.juku2024.juku

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.juku2024.juku.adapter.HistoryAdapter
import com.juku2024.juku.base.BaseActivity
import com.juku2024.juku.db.NoteRoomUtils
import com.juku2024.juku.db.entity.HistoryEntity
import com.juku2024.juku.tools.AppUtils
import com.juku2024.juku.viewmodel.HistoryViewModel
import com.juku2024.juku.widget.HeaderView
import com.juku2024.juku.widget.LoadingView

class HistoryActivity: BaseActivity(), View.OnClickListener {

    private lateinit var headView: HeaderView
    private lateinit var loadingView: LoadingView
    private lateinit var recyclerHistory: RecyclerView
    private lateinit var deleteTv: TextView
    private lateinit var selectAllTv: TextView
    private lateinit var bottomInfoLl: View

    private val adapter by lazy { HistoryAdapter(ArrayList()) }
    private val viewModel by lazy { getViewModel(HistoryViewModel::class.java) }

    override fun getLayoutResId(): Int {
        return R.layout.activity_favorite
    }


    override fun initView() {
        super.initView()

        headView = findViewById(R.id.headView_favorite)
        loadingView = findViewById(R.id.loadingView_favorite)
        recyclerHistory = findViewById(R.id.recyclerHistory)
        deleteTv = findViewById(R.id.delete_tv_favorite)
        selectAllTv = findViewById(R.id.select_all_tv_favorite)
        bottomInfoLl = findViewById(R.id.bottom_info_ll_favorite)
        
        headView.setTitle(getString(R.string.history))
        recyclerHistory.layoutManager = LinearLayoutManager(this)
        recyclerHistory.setHasFixedSize(true)
        recyclerHistory.adapter = adapter
    }

    override fun init(savedInstanceState: Bundle?) {
        loadingView.showLoading()

        viewModel.getHistory({
            if (isActivityNotActive()) return@getHistory
            loadingView.hideLoading()
            adapter.setList(it)
        }, {
            if (isActivityNotActive()) return@getHistory
            loadingView.hideLoading()
            loadingView.showEmptyStatus(getString(R.string.no_history_list))
            headView.hideEditView()
        })
    }

    override fun bindEvent() {
        super.bindEvent()
        headView.setOnEditClickListener(this)
        deleteTv.setOnClickListener(this)
        selectAllTv.setOnClickListener(this)

        adapter.setOnItemChildClickListener { _, _, position ->
            checkSelectState(adapter.data[position])
            adapter.notifyItemChanged(position)
        }
        adapter.setOnItemClickListener { _, _, position ->
            checkSelectState(adapter.data[position])
            adapter.notifyItemChanged(position)
            if (bottomInfoLl.visibility != View.VISIBLE) {
                VideoDetailActivity.toVideoDetail(this, adapter.data[position].videoId, adapter.data[position].name)
            }
        }
    }

    override fun onClick(p0: View?) {
        when (p0!!) {
            selectAllTv -> selectOrCancelAll()
            deleteTv -> delete()
            else -> clickEdit()
        }
    }


    private fun checkSelectState(item: HistoryEntity) {
        item.isSelect = !item.isSelect
        var nums = 0
        adapter.data.forEach {
            if (it.isSelect) {
                nums++
            }
        }
        if (nums >= adapter.data.size) {
            selectAllTv.text = AppUtils.getString(R.string.cancel_select_all)
            deleteTv.text = String.format(AppUtils.getString(R.string.delete_num), nums)
            deleteTv.setTextColor(AppUtils.getColor(R.color.color_text_light))
        } else {
            if (nums > 0) {
                deleteTv.text = String.format(AppUtils.getString(R.string.delete_num), nums)
                deleteTv.setTextColor(AppUtils.getColor(R.color.color_text_light))
            } else {
                deleteTv.text = AppUtils.getString(R.string.delete)
                deleteTv.setTextColor(AppUtils.getColor(R.color.color_text_dark))
            }
            selectAllTv.text = AppUtils.getString(R.string.select_all)
        }
    }


    private fun delete() {
        showErrorDialog(
            "您确认删除选中的播放历史记录吗？",
            getString(R.string.confirm), {
                hideErrorDialog()
                val currentList = adapter.data.filter { it.isSelect }
                adapter.data.removeAll(currentList)
                NoteRoomUtils.getInstance().historyDao().delete(currentList)
                adapter.notifyDataSetChanged()
                val count = adapter.data.count { it.isSelect }
                deleteTv.text = String.format(AppUtils.getString(R.string.delete_num), count)

                if (adapter.data.isEmpty()) {
                    bottomInfoLl.visibility = View.GONE
                    headView.setMenuText(getString(R.string.edit))
                    adapter.isEditStatus = false
                    loadingView.showEmptyStatus(getString(R.string.no_favorite_list))
                }
            }, getString(R.string.cancel), {
                hideErrorDialog()
            }
        )
    }

    private fun selectOrCancelAll() {
        if (selectAllTv.text == AppUtils.getString(R.string.select_all)) {
            selectAllTv.text = AppUtils.getString(R.string.cancel_select_all)
            deleteTv.text =
                String.format(AppUtils.getString(R.string.delete_num), adapter.data.size)
            deleteTv.setTextColor(AppUtils.getColor(R.color.color_text_light))
            adapter.data.forEach {
                it.isSelect = true
            }
        } else {
            deleteTv.text = AppUtils.getString(R.string.delete)
            deleteTv.setTextColor(AppUtils.getColor(R.color.color_text_dark))
            selectAllTv.text = AppUtils.getString(R.string.select_all)
            adapter.data.forEach {
                it.isSelect = false
            }
        }
        adapter.notifyDataSetChanged()
    }

    private fun clickEdit() {
        if (adapter.data.size == 0) {
            return
        }
        adapter.isEditStatus = !(adapter.isEditStatus)
        adapter.data.forEach {
            it.isSelect = false
        }

        selectAllTv.text = AppUtils.getString(R.string.select_all)
        deleteTv.text = AppUtils.getString(R.string.delete)
        deleteTv.setTextColor(AppUtils.getColor(R.color.color_text_dark))
        adapter.notifyDataSetChanged()

        val text = if (adapter.isEditStatus) {
            bottomInfoLl.visibility = View.VISIBLE
            AppUtils.getString(R.string.cancel)
        } else {
            bottomInfoLl.visibility = View.GONE
            AppUtils.getString(R.string.edit)
        }
        if (!TextUtils.isEmpty(text)) {
            headView.setMenuText(text)
        }
    }

    @Suppress("DEPRECATION")
    @Deprecated("Deprecated in Java")
    override fun onBackPressed() {
        if (adapter.isEditStatus) {
            adapter.isEditStatus = false
            adapter.notifyDataSetChanged()
            bottomInfoLl.visibility = View.GONE
            headView.setMenuText(AppUtils.getString(R.string.edit))
            return
        }
        super.onBackPressed()
    }
}